import instance from "@/api/request.js";
import {ElMessage} from "element-plus";
import {ref} from "vue";
import {usePagination} from "@/composables/usePagination.js";

async function fetchRoleList(params) {
    return new Promise((resolve, reject) => {
        try {
            instance.post("/role/page", params).then((res) => {
                resolve(res.data);
            });
        } catch (error) {
            ElMessage.error("加载失败");
            reject(error);
        }
    });
}

export default function () {
    const queryParams = reactive({
        description: '', // 用于根据角色编码/角色名称/角色描述进行模糊查询
        status: null, // 启用状态
    });

    // 加载状态控制
    const loading = ref(false);

    // 查询分页参数
    const {current, total, size} = usePagination(10);


    // 表单查询结果
    const roleList = ref([])

    const loadData = async () => {
        loading.value = true;
        try {
            const res = await fetchRoleList({
                current: current.value,
                size: size.value,
                ...queryParams,
            });
            roleList.value = res.records;
            total.value = res.total;
        } catch (err) {
            ElMessage.error("加载失败");
        } finally {
            loading.value = false;
        }
    }

    const search = () => {
        loadData();
    }

    const reset = () => {
        queryParams.description = ""
        queryParams.status = null
        search();
    }
    // 8. 分页事件
    const handleCurrentChange = (newPage) => {
        current.value = newPage
        loadData();
    };

    const handleSizeChange = (newSize) => {
        size.value = newSize
        loadData();
    };
    return {
        queryParams,
        loading,
        current,
        total,
        size,
        roleList,
        loadData,
        search,
        reset,
        handleCurrentChange,
        handleSizeChange
    }
}